package com.bw.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bw.aop.MyLog;
import com.bw.domain.SysUser;
import com.bw.service.SysUserService;
import com.bw.utils.common.JWTUtils;
import com.bw.utils.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author bobo棒
 * @date 2024年04月08日 10:23
 */

@RequestMapping("auth")
@RestController
public class AuthController {
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    SysUserService sysUserService;


    @RequestMapping("login")
    public Result login(@RequestBody SysUser sysUser){
       //  1.获取前端传递的验证码
        String code = sysUser.getCode();
        String redisCode  = (String) redisTemplate.opsForValue().get(sysUser.getUid());
        if(!code.equals(redisCode)){
           return Result.fail("验证码错误");
        }
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,sysUser.getUsername());
        SysUser dbUser = sysUserService.getOne(wrapper);
        if(null ==dbUser){
            return Result.fail("用户名错误");
        }
        if(!dbUser.getPassword().equals(sysUser.getPassword())){
            return Result.fail("密码错误");
        }
        //登录成功
       // redis处理验证码的数据
        redisTemplate.delete(sysUser.getUid());

        String token = JWTUtils.createToken(dbUser.getId(), 5 * 60);

        return Result.success(token);
    }


    /**
     * 生成验证码的次数 控制
     * @param uid
     * @return
     */
    @RequestMapping("checkNum")
    public Result checkNum(String uid){
        Long num = redisTemplate.opsForValue().increment("num:" + uid, 1);
        if(num>3){
            //1分钟后 删除该key
            redisTemplate.expire("num:" + uid,1, TimeUnit.MINUTES);
            return Result.fail("1分钟内请求>3次了,过于频繁");
        }else{
            return Result.success();
        }

    }

    @MyLog
    @RequestMapping("getImageCode")
    public void getImageCode(String uid, HttpServletResponse response) throws IOException {
        //定义图形验证码的长、宽、验证码字符数、干扰元素个数
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        captcha.write(response.getOutputStream());
        redisTemplate.opsForValue().set(uid,captcha.getCode(),2, TimeUnit.MINUTES);
    }
}
